package com.laoyu.common.db;

import com.alibaba.fastjson.JSONObject;
import org.yaml.snakeyaml.Yaml;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class YamlResourceLoader {
  private String filePath;
  private LinkedHashMap<String, Object> resourceMap = null;

  public YamlResourceLoader setPath(String path) {
    this.filePath = path;
    return this;
  }

  @SuppressWarnings("unchecked")
  public YamlResourceLoader load() {
    assert filePath != null;
    Yaml yaml = new Yaml();
    Object load = yaml.load(this.getClass().getClassLoader().getResourceAsStream(filePath));
    this.resourceMap = (LinkedHashMap<String, Object>) load;
    return this;
  }


  @SuppressWarnings("unchecked")
  public <T> List<T> getList(String key, Class<T> target) {
    Object object = getObject(key, this.resourceMap);
    if (!(object instanceof List<?>)) {
      throw new RuntimeException("the node type is not list,please check your configuration!");
    }
    List<T> result = new ArrayList<>();
    List<T> objList = (List<T>) object;
    objList.forEach(
        e -> {
          result.add(JSONObject.parseObject(JSONObject.toJSONString(e), target));
        });
    return result;
  }


  public <T> T getObject(String key, Class<T> target) {
    Object object = getObject(key, this.resourceMap);
    return JSONObject.parseObject(JSONObject.toJSONString(object), target);
  }

  public String getString(String key) {
    Object object = getObject(key, this.resourceMap);
    return object == null ? null : object.toString();
  }

  @SuppressWarnings("unchecked")
  private Object getObject(String key, LinkedHashMap<String, Object> originResourceMap) {
    Object result = null;
    String[] keys = key.split("\\.");
    for (int i = 0; i < keys.length; i++) {
      if (i == keys.length - 1) {
        result = get(keys[i], originResourceMap);
        continue;
      }
      Object o = get(keys[i], originResourceMap);
      originResourceMap = (LinkedHashMap<String, Object>) o;
    }
    return result;
  }

  private Object get(String key, LinkedHashMap<String, Object> resourceMap) {
    return resourceMap.get(key);
  }
}
